﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;

namespace _43文件操作io流作业
{
    internal class Inifile
    {
        //创建字典存放键值 第二层嵌套字典
        private Dictionary<string, Dictionary<string, string>> dic = new Dictionary<string, Dictionary<string, string>>();

        public void ReadFile()
        {
            string path = @"E:\C#\mylearn\CsharpBase\43文件操作io流作业\config.txt";
            string file = File.ReadAllText(path); //读取ini所有文本
                                                  // 将ini字符串转成数组
            string[] array = file.Split('\n');
            string key = "";
            //遍历拿到的数组筛选主键和值
            for (int i = 0; i < array.Length; i++)
            {
                if (array[i].StartsWith("["))
                {
                    key = array[i].Substring(1, array[i].Length - 2);//拿到主键内容
                    dic.Add(key, new Dictionary<string, string>());//将主键添加到外层字典键
                }
                //判断是否为内层键值对
                else if (array[i].Contains("="))
                {
                    //分割内层键值对
                    string[] key1 = array[i].Split('=');

                    //将内层键值分别加进主键key
                    dic[key].Add(key1[0].TrimEnd(), key1[1].TrimStart());
                }
            }
        }

        public string GetString(string key, string key1)
        {
            return dic[key][key1];
        }

        //bool
        public bool GetBool(string key, string key1)
        {
            return bool.Parse(GetString(key, key1));
        }
    }
}